#!/usr/bin/env python
#-------------------------------------------------------------------------------
##	\file gen-proj.py
##
##	\brief
##	Generate Keil project files from a base file set.
##	In this case, the base file set is "blinky".
##	The goal is to be able to generate a complete set of directories
##	from a list of files.
##
#	$Id: gen-proj.py 301 2014-10-28 20:44:14Z ac.verbeck@gmail.com $
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#	The MIT License (MIT)
#
#	Copyright (c) 2014 A.C. Verbeck
#
#	Permission is hereby granted, free of charge, to any person obtaining a copy
#	of this software and associated documentation files (the "Software"), to deal
#	in the Software without restriction, including without limitation the rights
#	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#	copies of the Software, and to permit persons to whom the Software is
#	furnished to do so, subject to the following conditions:
#
#	The above copyright notice and this permission notice shall be included in
#	all copies or substantial portions of the Software.
#
#	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#	THE SOFTWARE.
#-------------------------------------------------------------------------------

__author__ = '$Author: ac.verbeck@gmail.com $'
__version__ = '$Rev: 301 $'
__date__ = '$Date: 2014-10-28 13:44:14 -0700 (Tue, 28 Oct 2014) $'
__license__ = 'MIT'

import os
import sys
import csv
import time
import logging

#-------------------------------------------------------------------------------
##	gen_directory -- generate the project directory
#
##	\brief
##	This function generates project directories
#
##	\param	path	directory path to generate
#-------------------------------------------------------------------------------
def gen_directory(path):
	try: 
		os.makedirs(path)
	except OSError:
		if not os.path.isdir(path):
			raise
	logging.debug('Created directory: %s',path)


#-------------------------------------------------------------------------------
##	gen_proj_file -- generate project files
#
##	\brief
##	This function generates project files with the following parameters
#
##	\param	opt		options passed from command line
##	\param	p_name	output file name (used for sub-dir and substitution too)
##	\param	ext		the output file extension
#-------------------------------------------------------------------------------
def gen_proj_file(opt, p_name, ext):
	path = "{}/{}.{}".format(p_name, p_name, ext)
	base = '{}.{}'.format(opt.base, ext)
	with open(path, 'wt') as f_out:
		with open(base, 'rt') as f_in:
			for line in f_in:
				f_out.write(line.replace('blinky', p_name))
	logging.debug('Created %s: %s', ext, p_name)


#-------------------------------------------------------------------------------
##	gen_project -- generate a complete Keil project
#
##	\brief Open the csv, and loop through it:
##	- create a directory with the sym name
##	- create a *.uvprojx file
##	- create a *.uvoptx file
#-------------------------------------------------------------------------------
def gen_project(opt):
	with open(opt.input, 'rb') as f_in:
		proj_reader = csv.reader(f_in, dialect='excel')
		for row in proj_reader:
			proj_name = row[0]
			logging.debug('Starting project: %s', proj_name)
			gen_directory(proj_name)
			gen_proj_file(opt, proj_name, 'uvprojx')
			gen_proj_file(opt, proj_name, 'uvoptx')
			logging.debug('Completed project: %s\n',row[0])


#-------------------------------------------------------------------------------
##	parse_args -- parse command line arguments
#
##	\brief
#   Parse generate project arguments:
#
##	\param	input	options passed from command line
##	\param	base	the project base name
##	\param	log		process log information
#-------------------------------------------------------------------------------
def parse_args():
	import argparse
	ap = argparse.ArgumentParser(description="Keil project generator")
	
	ap.add_argument("-i", "--input", default="projects.csv",
					help="Input file name (default: %(default)s)")
	ap.add_argument("-b", "--base", default="rom",
					help="Base file name (default: %(default)s)")
	ap.add_argument("-l", "--log", default="projects.log",
					help="Logging file name (default: %(default)s)")

	if len(sys.argv) == 1:
		ap.print_help()
		sys.exit(1)
	return ap.parse_args()


#-------------------------------------------------------------------------------
#   logging configuration
#-------------------------------------------------------------------------------
def log_init(opt):
	fmtr='%(asctime)s | %(name)s | %(levelname)s | %(message)s'
	logging.basicConfig(level=logging.DEBUG, filename=opt.log, format=fmtr)


#-------------------------------------------------------------------------------
#   main:
#   - Parse the arguments
#	- Start logging
#   - Generate the projects
#-------------------------------------------------------------------------------
def main():
	options = parse_args()
	log_init(options)
	logging.debug('Log Start')
	gen_project(options)
	logging.debug('Log End')
	return 0


#-------------------------------------------------------------------------------
#   Main processing
#-------------------------------------------------------------------------------
if __name__ == "__main__":
	sys.exit(main())

#
#   End: gen-proj.py
#
